
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

public class Helloservlet implements Servlet {
    /**
     * 初始化servlet，服务器立即调用init方法，类似于类的实例化对象的构造器，一个servlet只被调用一次
     * servlet接口中不含有成员属性servletconfig，需要自己重新定义，再初始化
     * @param config
     * @throws ServletException
     */
    private ServletConfig config = null;
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public ServletConfig getServletConfig() {
        return this.config;
    }

    /**
     * 处理请求
     * @param req
     * @param res
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        ServletContext context = this.getServletConfig().getServletContext();
        context.setAttribute("username",new String("LiuDH"));
        res.getWriter().print((String) context.getAttribute("username"));
    }


    @Override
    public String getServletInfo() {
        return null;
    }

    /**
     * 最后结束都会调用此方法，一般用于释放资源
     */
    @Override
    public void destroy() {

    }

    /*
    //利用继承httpservlet回馈servlet对象
        @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //ServletOutputStream outputStream =resp.getOutputStream();
//        PrintWriter writer = resp.getWriter(); //响应流
//        writer.print("Hello,Serlvet");
        ServletContext context = this.getServletContext();
        String username = "hello,i am lihua";
        context.setAttribute("username",username);
        resp.getWriter().print(context.getAttribute("username"));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
     */

}
